package net.wanho.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.google.code.kaptcha.Constants;
import net.wanho.vo.AjaxResult;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class KaptchaFilter extends AccessControlFilter {
    // 是否允许访问,判断验证码是否正确
    @Override
    protected boolean isAccessAllowed(ServletRequest servletRequest, ServletResponse servletResponse, Object o) throws Exception {
        HttpServletRequest request = WebUtils.toHttp(servletRequest);
        HttpServletResponse response = WebUtils.toHttp(servletResponse);
        String sessionCode = (String) request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
        String validateCode = WebUtils.getCleanParam(servletRequest, "validateCode");
        if(!sessionCode.equalsIgnoreCase(validateCode)){
            response.setContentType("application/json;charset=utf-8");
            PrintWriter out = response.getWriter();
            AjaxResult ajaxResult = new AjaxResult(false,500,"验证码不正确",null);
            out.print(JSON.toJSONString(ajaxResult));
            out.flush();
            out.close();
        }
        return true;
    }

    // 访问拒绝给予的提示
    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        HttpServletRequest request = WebUtils.toHttp(servletRequest);
        request.getSession().setAttribute("errMsg","验证码不正确");
        saveRequestAndRedirectToLogin(servletRequest,servletResponse);
        return false;
    }
}
